package main

import (
	"fmt"
	"net"
)

func main() {
	//创建udp地址
	udpAddr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:9010")
	//服务端建立监听
	serverConn, err := net.ListenUDP("udp", udpAddr)
	if err == nil{
		fmt.Println("正在9010端口监听。。。")
	}else {
		fmt.Println(err)
		return
	}

	defer func() {
		serverConn.Close()
		fmt.Println("main over!")
	}()

	//与客户端IO
	//建立1024字节缓冲区
	for {
		buffer := make([]byte, 1024)
		n, remoteAddress, _ := serverConn.ReadFromUDP(buffer)
		//从buffer读取数据
		contents := buffer[:n]
		//打印读到的地址和数据
		fmt.Printf("客户端：%v %v\n",remoteAddress,string(contents))
		//回复本条消息
		serverConn.WriteToUDP(contents, remoteAddress)
	}

}